#pragma once
#include<iostream>
#include<cstring>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include"Log.hpp"

#define BACKLOG 5
//封装sock接口便于使用
class Sock
{
public:
    static int Socket()
    {
        int sock=socket(AF_INET,SOCK_STREAM,0);
        if(sock<0){
            LOG(FATA,"socket err");
            exit(SocketErr);
        }
        LOG(INFO,"socket success");
        return sock;
    }
    static void Bind(int sock,uint16_t port)
    {
        struct sockaddr_in local;
        bzero(&local,sizeof(local));
        local.sin_family=AF_INET;
        local.sin_port=htons(port);
        local.sin_addr.s_addr=INADDR_ANY;
        if(bind(sock,(struct sockaddr*)&local,sizeof(local))<0){
            LOG(FATA,"bind err");
            exit(BindErr);
        }
        LOG(INFO,"bind success");
    }
    static void Listen(int sock)
    {
        if(listen(sock,BACKLOG)<0)
        {
            LOG(FATA,"listen err");
            exit(ListenErr);
        }
        LOG(INFO,"listen success");
    }
    static int Accept(int sock)
    {
        struct sockaddr_in peer;
        socklen_t len=sizeof(peer);
        int s=accept(sock,(struct sockaddr*)&peer,&len);
        if(s<0)
            LOG(WARNING,"accept err");
        LOG(INFO,"accept success");
        return s;
    }
    static void SetSockOpt(int sock)
    {
        int opt=1;
        setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
        LOG(INFO,"setsockopt success");
    }
    static void GetLine(int sock,std::string line)
    {
        char c='X';
        //不同平台结束符不同 '\r' '\r\n' '\n'
        while(c!='\n')
        {
            ssize_t s=recv(sock,&c,1,0);
            if(s>0)
            {
                if(c=='\r')//探测后一个字符
                {
                    ssize_t ss=recv(sock,&c,1,MSG_PEEK);
                    if(ss>0&&c=='\n')
                        recv(sock,&c,1,0);//取出
                    else
                        c='\n';
                }
                if(c!='\n')
                    line.push_back(c);
            }
        }
    }
};
